package com.chengh.nami.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chengh.nami.common.exception.BizException;
import com.chengh.nami.common.request.PageQuery;
import com.chengh.nami.common.response.PageData;
import com.chengh.nami.common.utils.StringUtils;
import com.chengh.nami.system.domain.dto.UserDto;
import com.chengh.nami.system.domain.vo.UserVo;
import com.chengh.nami.system.mapper.SysUserMapper;
import com.chengh.nami.common.domain.pojo.SysRole;
import com.chengh.nami.common.domain.pojo.SysUser;
import com.chengh.nami.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author chengh
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Override
    public List<SysUser> getInfos() {
        return this.list();
    }

    @Override
    public PageData<UserVo> getUserList(UserDto userDto, PageQuery pageQuery) {
        Page<UserVo> page = pageQuery.build();
        Page<UserVo> userList = baseMapper.getUserList(page, userDto);
        return PageData.build(userList);
    }

    @Override
    public SysUser getUserByName(String userName) {
        return this.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUsername, userName));
    }

    @Override
    public List<SysRole> getSysRoleByUserId(Long userId) {
        return this.baseMapper.selectSysRoleByUserId(userId);
    }

    @Override
    public UserVo getUserInfoById(Long id) {
        return this.baseMapper.selectUserInfoById(id);
    }

    @Override
    public boolean checkUserNameUnique(String username) {
        if(StringUtils.isEmpty(username)) {
            throw new BizException("用户名不能为空！");
        }
        Long count = this.baseMapper.selectCount(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUsername, username));
        log.info("实际行数 {}", count);
        return count > 0;
    }

    @Override
    public boolean insertUser(SysUser user) {
        int insertCount = this.baseMapper.insert(user);
        return insertCount > 0;
    }
}
